import { useState } from 'react';
import { Link } from 'react-router-dom';
import { Button } from '@kernelproxy/ui';
import { useLanguage, useLocalizedLink } from '@kernelproxy/i18n';
import { authService } from '../services/auth';
import { useToast } from '../contexts/ToastContext';

const ForgotPassword = () => {
  const [email, setEmail] = useState('');
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState('');
  const { language } = useLanguage();
  const { getLink } = useLocalizedLink();
  const toast = useToast();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    try {
      const result = await authService.sendPasswordRecovery(email);
      if (result.success) {
        setSuccess(true);
        toast.success(language === 'zh-CN' ? '重置邮件已发送，请检查您的邮箱' : 'Reset email sent, please check your inbox');
      } else {
        const errorMsg = language === 'zh-CN' ? '发送重置邮件失败，请重试' : 'Failed to send reset email, please try again';
        setError(errorMsg);
        toast.error(errorMsg);
      }
    } catch (err) {
      const errorMsg = language === 'zh-CN' ? '发送重置邮件失败，请重试' : 'Failed to send reset email, please try again';
      setError(errorMsg);
      toast.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center px-4 sm:px-6 lg:px-8 transition-colors duration-300">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <a href="https://kernelproxy.com" className="inline-flex items-center justify-center">
            <span className="text-3xl font-bold text-[#00d4ff]">kernel</span>
            <span className="text-3xl font-bold text-[#0f1c3f] dark:text-white">Proxy</span>
          </a>
          <h2 className="mt-6 text-3xl font-bold text-gray-900 dark:text-white">
            {language === 'zh-CN' ? '重置密码' : 'Reset Password'}
          </h2>
          <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
            {language === 'zh-CN' ? '记得密码？' : 'Remember your password?'}{' '}
            <Link to={getLink('/login')} className="font-medium text-[#00d4ff] hover:text-[#0f1c3f] dark:hover:text-[#00d4ff]/80">
              {language === 'zh-CN' ? '返回登录' : 'Back to login'}
            </Link>
          </p>
        </div>

        <div className="bg-white dark:bg-gray-800 py-8 px-4 shadow-lg sm:rounded-lg sm:px-10 transition-colors duration-300">
          {error && (
            <div className="mb-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md">
              <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
            </div>
          )}

          {success ? (
            <div className="text-center">
              <div className="mb-4 p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-md">
                <p className="text-sm text-green-600 dark:text-green-400">
                  {language === 'zh-CN' 
                    ? '重置邮件已发送！请检查您的邮箱并点击链接重置密码。' 
                    : 'Reset email sent! Please check your inbox and click the link to reset your password.'}
                </p>
              </div>
              <Link to={getLink('/login')}>
                <Button fullWidth variant="gradient">
                  {language === 'zh-CN' ? '返回登录' : 'Back to Login'}
                </Button>
              </Link>
            </div>
          ) : (
            <form className="space-y-6" onSubmit={handleSubmit}>
              <div>
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
                  {language === 'zh-CN'
                    ? '输入您的邮箱地址，我们将向您发送重置密码的链接。'
                    : 'Enter your email address and we\'ll send you a link to reset your password.'}
                </p>
                <label htmlFor="email" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                  {language === 'zh-CN' ? '邮箱地址' : 'Email address'}
                </label>
                <div className="mt-1">
                  <input
                    id="email"
                    name="email"
                    type="email"
                    autoComplete="email"
                    required
                    value={email}
                    onChange={e => setEmail(e.target.value)}
                    className="appearance-none block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-[#00d4ff] focus:border-[#00d4ff] transition-colors duration-300"
                  />
                </div>
              </div>

              <div>
                <Button type="submit" fullWidth variant="gradient" disabled={loading}>
                  {loading 
                    ? (language === 'zh-CN' ? '发送中...' : 'Sending...') 
                    : (language === 'zh-CN' ? '发送重置链接' : 'Send Reset Link')}
                </Button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
};

export default ForgotPassword;
